package com.ruoyi.web.controller.inventory;

import com.ruoyi.asset.domain.AssetDetail;
import com.ruoyi.asset.service.IAssetDetailService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.Global;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.inventory.domain.Inventory;
import com.ruoyi.inventory.domain.InventoryByIdDetail;
import com.ruoyi.inventory.domain.InventoryDetail;
import com.ruoyi.inventory.domain.LostScrap;
import com.ruoyi.inventory.service.IInventoryDetailService;
import com.ruoyi.inventory.service.IInventoryService;
import com.ruoyi.inventory.service.ILostScrapService;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * inventoryController
 * 
 * @author ruoyi
 * @date 2019-10-29
 */
@Controller
@RequestMapping("/inventory/inventory")
public class InventoryController extends BaseController
{
    private String prefix = "inventory";
    @Autowired
    private IInventoryDetailService inventoryDetailService;
    @Autowired
    private IInventoryService inventoryService;
    @Autowired
    private IAssetDetailService assetDetailService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysDictDataService dictDataService;
    @Autowired
    private ILostScrapService lostScrapService;

    @RequiresPermissions("inventory:inventory:view")
    @GetMapping("")
    public String inventory()
    {
        return prefix + "/inventory";
    }

    @GetMapping("/inventory/{param}")
    public String inventoryDetail(@PathVariable("param") String param,ModelMap modelMap)
    {
        String[] strings=param.split(",");
        modelMap.put("inventoryId",strings.length>0?strings[0]:null);
        modelMap.put("assetNo",strings.length>1?strings[1]:null);
        return prefix + "/inventory";
    }

    /**
     * 盘点信息
     */
    @RequiresPermissions("inventory:inventory:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(InventoryDetail inventory)
    {
        startPage();
        List<InventoryDetail> list = inventoryDetailService.selectInventoryDetailList(inventory);
        return getDataTable(list);
    }

    /**
     * 导出盘点信息列表
     */
    @Log(title = "导出盘点信息", businessType = BusinessType.EXPORT)
    @RequiresPermissions("inventory:inventory:exportDetail")
    @PostMapping("/exportDetail")
    @ResponseBody
    public AjaxResult exportDetail(InventoryDetail inventory)
    {
        List<InventoryDetail> list = inventoryDetailService.selectInventoryDetailList(inventory);
        ExcelUtil<InventoryDetail> util = new ExcelUtil<InventoryDetail>(InventoryDetail.class);
        return util.exportExcel(list, "盘点信息");
    }

    /**
     * 导出盘点汇总列表
     */
    @Log(title = "导出盘点汇总信息", businessType = BusinessType.EXPORT)
    @RequiresPermissions("inventory:inventoryAll:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(InventoryByIdDetail inventory)
    {
        List<InventoryByIdDetail> list = inventoryDetailService.selectAllListById(inventory);
        for (InventoryByIdDetail detail:list) {
            if (StringUtils.isNotBlank(detail.getAssetType())){
                detail.setAssetType(dictDataService.selectDictLabel("asset_type",detail.getAssetType()));
            }
        }
        ExcelUtil<InventoryByIdDetail> util = new ExcelUtil<InventoryByIdDetail>(InventoryByIdDetail.class);
        return util.exportExcel(list, "盘点汇总信息");
    }

    /**
     * 新增inventory
     */
    @GetMapping("/add")
    public String add(ModelMap modelMap)
    {
//        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyyMMddHHmmss");
//        modelMap.put("oddNumber",dateFormat.format(new Date())+"");
        return prefix + "/add";
    }

    /**
     * 修改inventory
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        InventoryByIdDetail inventory = inventoryDetailService.selectInventoryDetailById(id);
        mmap.put("inventory", inventory);
        return prefix + "/edit";
    }

    /**
     * 修改保存inventory
     */
    @RequiresPermissions("inventory:inventory:edit")
    @Log(title = "inventory", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(AssetDetail assetDetail)
    {
        Inventory inventory=new Inventory();
        inventory.setStatus("0");
        List<Inventory> inventories=inventoryService.selectInventoryList(inventory);
        if (CollectionUtils.isEmpty(inventories)){
            return AjaxResult.error("未发起盘点或盘点已结束！");
        }

        //判断是否进行遗失报废
        LostScrap lostScrapParam=new LostScrap();
        lostScrapParam.setInventoryNo(assetDetail.getId()+"-"+assetDetail.getNo());
        List<LostScrap> lostScraps=lostScrapService.selectLostScrapList(lostScrapParam);
        if (!CollectionUtils.isEmpty(lostScraps)){
            return AjaxResult.error("该资产已遗失或报废！");
        }

        InventoryDetail inventoryDetail=new InventoryDetail();
        inventoryDetail.setCreateBy(ShiroUtils.getUserId().toString());
        inventoryDetail.setAssetId(new Long(assetDetail.getId()));
        inventoryDetail.setInventoryNo(assetDetail.getId()+"-"+assetDetail.getNo());
        inventoryDetail.setInventoryId(inventories.get(0).getId()+"");
        //查询本次是否有过盘点
        List<InventoryDetail> details=inventoryDetailService.selectInventoryDetailList(inventoryDetail);
        if (CollectionUtils.isEmpty(details)){
            inventoryDetail.setStatus(assetDetail.getAgreementStatus());
            inventoryDetail.setRemark(assetDetail.getRemark());
            inventoryDetailService.insertInventoryDetail(inventoryDetail);
        }
//        else{
//            inventoryDetail=details.get(0);
//            inventoryDetail.setStatus(assetDetail.getAgreementStatus());
//            inventoryDetail.setRemark(assetDetail.getRemark());
//            inventoryDetail.setUpdateBy(ShiroUtils.getUserId()+"");
//            inventoryDetailService.updateInventoryDetail(inventoryDetail);
//        }

        //报废
        if("1".equals(assetDetail.getScrapStatus())){
            LostScrap lostScrap=new LostScrap();
            lostScrap.setCreateBy(ShiroUtils.getUserId().toString());
            lostScrap.setDelFlag("0");
            lostScrap.setStatus("2");
            lostScrap.setAssetId(new Long(assetDetail.getId()));
            lostScrap.setInventoryNo(assetDetail.getId()+"-"+assetDetail.getNo());
            lostScrap.setInventoryId(inventories.get(0).getId());
            lostScrap.setRemark(assetDetail.getRemark());
            lostScrapService.insertLostScrap(lostScrap);
            return AjaxResult.success(inventories.get(0).getId());
        }

        return AjaxResult.success(inventories.get(0).getId());
    }

    /**
     * 修改inventory
     */
    @GetMapping("/editAsset/{id}")
    public String editAsset(@PathVariable("id")String id, ModelMap mmap)
    {
        AssetDetail assetDetail=assetDetailService.selectAssetDetailById(id);
        mmap.put("assetDetail", assetDetail);
        SysUser sysUser=new SysUser();
        if (StringUtils.isNotBlank(assetDetail.getManageDept())){
            sysUser.setDeptId(Long.parseLong(assetDetail.getManageDept()));
            mmap.put("manageUserList", userService.selectUserList(sysUser));
        }
        if (StringUtils.isNotBlank(assetDetail.getDeptId())){
            sysUser.setDeptId(Long.parseLong(assetDetail.getDeptId()));
            mmap.put("useUserList", userService.selectUserList(sysUser));
        }
        return prefix + "/edit";
    }

    /**
     * 删除inventory
     */
    @RequiresPermissions("inventory:inventory:remove")
    @Log(title = "inventory", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(inventoryDetailService.deleteInventoryDetailByIds(ids));
    }

    /**
     * 手机盘点
     */
    @GetMapping("/mobileInventory/{param}")
    public String mobileInventory(@PathVariable("param")String param, ModelMap mmap)
    {
        String[] strings=param.split(",");

        Inventory inventoryParam=new Inventory();
        inventoryParam.setStatus("0");
        List<Inventory> inventories=inventoryService.selectInventoryList(inventoryParam);
        List<InventoryDetail> inventoryDetails=new ArrayList<InventoryDetail>();
        if (!CollectionUtils.isEmpty(inventories)){
            inventoryParam=inventories.get(0);
            InventoryDetail inventoryDetail=new InventoryDetail();
            inventoryDetail.setAssetId(new Long(strings[0]));
            inventoryDetail.setInventoryId(inventoryParam.getId().toString());
            inventoryDetail.setInventoryNo(strings[0]+"-"+strings[1]);
            inventoryDetails=inventoryDetailService.selectInventoryDetailList(inventoryDetail);
        }
        mmap.put("repeatFlag",!CollectionUtils.isEmpty(inventoryDetails)?true:false);

        AssetDetail assetDetail=assetDetailService.selectAssetDetailById(strings[0]);
        //资产内序号
        assetDetail.setNo(strings.length>1?strings[1]:null);
        if (StringUtils.isNotBlank(assetDetail.getUseUser())){
            assetDetail.setUseUser(userService.selectUserById(Long.parseLong(assetDetail.getUseUser())).getUserName());
        }
        if (StringUtils.isNotBlank(assetDetail.getManageUser())){
            assetDetail.setManageUser(userService.selectUserById(Long.parseLong(assetDetail.getManageUser())).getUserName());
        }
        if (StringUtils.isNotBlank(assetDetail.getDeptId())){
            SysUser sysUser=new SysUser();
            sysUser.setDeptId(Long.parseLong(assetDetail.getDeptId()));
            mmap.put("useUserList", userService.selectUserList(sysUser));
        }
        List<String> imgList=assetDetailService.findImg(strings[0]);

        //判断是否进行遗失报废
        LostScrap lostScrapParam=new LostScrap();
        lostScrapParam.setInventoryNo(assetDetail.getId()+"-"+assetDetail.getNo());
        List<LostScrap> lostScraps=lostScrapService.selectLostScrapList(lostScrapParam);
        mmap.put("lostScrapFlag",CollectionUtils.isEmpty(lostScraps)?false:true);

        mmap.put("imgUrl",CollectionUtils.isEmpty(imgList)?"":imgList.get(0));
        mmap.put("assetDetail", assetDetail);
        mmap.put("allFlag", strings.length>1?false:true);
        mmap.put("qrCodeUrl", Global.getQrCodeUrl());
        return prefix + "/mobileEdit";
    }
    /**
     * 盘点汇总
     */
    @RequiresPermissions("inventory:inventory:view")
    @GetMapping("inventoryAll")
    public String inventoryAll()
    {
        return prefix + "/inventoryAll";
    }
    /**
     * 盘点汇总
     */
    @PostMapping( "/inventoryAllList")
    @ResponseBody
    public TableDataInfo inventoryAllList(Inventory inventory)
    {
        startPage();
        List<Inventory> list = inventoryService.selectInventoryList(inventory);
        return getDataTable(list);
    }

    @RequiresPermissions("inventory:inventoryAll:add")
    @Log(title = "发起盘点", businessType = BusinessType.INSERT)
    @PostMapping( "/inventoryAllAdd")
    @ResponseBody
    public AjaxResult inventoryAllAdd()
    {
        Inventory inventoryParam=new Inventory();
        inventoryParam.setStatus("0");
        List<Inventory> inventories=inventoryService.selectInventoryList(inventoryParam);
        if (!CollectionUtils.isEmpty(inventories)){
            return AjaxResult.warn("上次盘点未结束");
        }
        Inventory inventory=new Inventory();
        inventory.setCreateBy(ShiroUtils.getUserId()+"");
        return toAjax(inventoryService.insertInventory(inventory));
    }

    @RequiresPermissions("inventory:inventoryAll:end")
    @Log(title = "结束盘点", businessType = BusinessType.UPDATE)
    @PostMapping( "/inventoryAllEdit")
    @ResponseBody
    public AjaxResult inventoryAllEdit(Long id)
    {
        Inventory inventory=new Inventory();
        inventory.setUpdateBy(ShiroUtils.getUserId()+"");
        inventory.setStatus("1");
        inventory.setId(id);
        return toAjax(inventoryService.updateInventory(inventory));
    }
    /**
     * 盘点汇总-查看
     */
    @GetMapping("inventoryAll/{id}")
    public String inventoryAllById(@PathVariable("id")String id, ModelMap mmap)
    {
        mmap.put("inventoryId",id);
        return prefix + "/inventoryAllById";
    }
    /**
     * 盘点汇总-查看
     */
    @PostMapping( "/allByIdList")
    @ResponseBody
    public TableDataInfo allByIdList(InventoryByIdDetail inventory)
    {
        startPage();
        List<InventoryByIdDetail> list = inventoryDetailService.selectAllListById(inventory);
        //资产图片
        List<AssetDetail> imgCountList=assetDetailService.selectImgCountByAssetId();
        Map<Integer,Integer> imgCountMap=imgCountList.stream().collect(Collectors.toMap(AssetDetail::getId,AssetDetail::getImgCount));
        //相符数量
        List<InventoryByIdDetail> yesCountList=inventoryDetailService.selectYesCountByAssetId(inventory.getInventoryId());
        Map<Long,Integer> yesCountMap=yesCountList.stream().collect(Collectors.toMap(InventoryByIdDetail::getAssetId,InventoryByIdDetail::getYesCount));
        //不相符数量
        List<InventoryByIdDetail> noCountList=inventoryDetailService.selectNoCountByAssetId(inventory.getInventoryId());
        Map<Long,Integer> noCountMap=noCountList.stream().collect(Collectors.toMap(InventoryByIdDetail::getAssetId,InventoryByIdDetail::getNoCount));

        int yesCount;
        int noCount;
        int noInventoryCount;
        for (InventoryByIdDetail inventoryByIdDetail:list) {
            Long assetId=inventoryByIdDetail.getAssetId();
            inventoryByIdDetail.setImgCount(imgCountMap.get(assetId.intValue())!=null?imgCountMap.get(assetId.intValue()):0);

            yesCount=yesCountMap.get(assetId)!=null?yesCountMap.get(assetId):0;
            inventoryByIdDetail.setYesCount(yesCount);

            noCount=noCountMap.get(assetId)!=null?noCountMap.get(assetId):0;
            inventoryByIdDetail.setNoCount(noCount);

            LostScrap lostScrap=new LostScrap();
            lostScrap.setAssetId(inventoryByIdDetail.getAssetId());
            List<LostScrap> lostScraps=lostScrapService.selectLostScrapList(lostScrap);
            inventoryByIdDetail.setLostScrapCount(CollectionUtils.isEmpty(lostScraps)?0:lostScraps.size());

            noInventoryCount= (int) (inventoryByIdDetail.getAmount()-yesCount-noCount-inventoryByIdDetail.getLostScrapCount());
            inventoryByIdDetail.setNoInventoryCount(noInventoryCount<=0?0:noInventoryCount);
        }
        return getDataTable(list);
    }

    /**
     * 盘点汇总-未盘到资产
     */
    @GetMapping("noInventory/{param}")
    public String noInventory(@PathVariable("param")String param, ModelMap mmap)
    {
        String[] strings=param.split(",");
        mmap.put("inventoryId",strings.length>0?strings[0]:null);
        mmap.put("assetId",strings.length>1?strings[1]:null);
        return prefix + "/noInventory";
    }

    /**
     * 盘点汇总-未盘到资产
     */
    @PostMapping( "/noInventoryList")
    @ResponseBody
    public TableDataInfo noInventoryList(InventoryDetail inventory)
    {
        AssetDetail assetDetail=assetDetailService.selectAssetDetailById(inventory.getAssetId().toString());
        List<String> allAssetNo=new ArrayList<String>();
        for(int i=1;i<=assetDetail.getAmount();i++) {
            allAssetNo.add(assetDetail.getId()+"-"+(i));
        }

        List<InventoryDetail> list = inventoryDetailService.selectInventoryDetailList(inventory);
        List<String> inventoryNoList=list.stream().map(InventoryDetail::getInventoryNo).collect(Collectors.toList());
        for (String inventoryNo:inventoryNoList) {
            allAssetNo.remove(inventoryNo);
        }

        LostScrap lostScrapParam=new LostScrap();
        lostScrapParam.setAssetId(inventory.getAssetId());
        List<LostScrap> lostScrapList=lostScrapService.selectLostScrapList(lostScrapParam);
        List<String> lostScrapNoList=lostScrapList.stream().map(LostScrap::getInventoryNo).collect(Collectors.toList());Collectors.toList();
        for (String inventoryNo:lostScrapNoList) {
            allAssetNo.remove(inventoryNo);
        }

        List<InventoryDetail> inventoryDetails=new ArrayList<>();
        for (String inventoryNo:allAssetNo) {
            InventoryDetail inventoryDetail=new InventoryDetail();
            inventoryDetail.setAssetCode(assetDetail.getAssetCode());
            inventoryDetail.setInventoryId(inventory.getInventoryId());
            inventoryDetail.setAssetNo(assetDetail.getAssetNo());
            inventoryDetail.setAssetName(assetDetail.getAssetName());
            inventoryDetail.setAssetModel(assetDetail.getAssetModel());
            inventoryDetail.setSpecifications(assetDetail.getSpecifications());
            inventoryDetail.setInventoryNo(inventoryNo);
            inventoryDetails.add(inventoryDetail);
        }
        return getDataTable(inventoryDetails);
    }
}
